<?php

class Cache_Manager implements ISingleton
{
    /**
     * Instance variable (Singleton)
     *
     * @var Cache_Manager
     */
    protected static $instance = null;

    /**
     * A native backend.
     *
     * @var Zend_Cache_Backend_Interface
     */
    private $_backend = null;

    /**
     * Generic Singleton's function.
     *
     * @return Cache_Manager
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    /**
     * Returns a global backend.
     *
     * @return Zend_Cache_Backend_Interface
     */
    public function getBackend()
    {
        if (!$this->_backend) {
            $this->_backend = $this->_getBackendNamespaced('global');
        }

        return $this->_backend;
    }

    /**
     * Cleans the whole cache.
     *
     * @return void
     */
    public function clean()
    {
    	$this->getBackend()->clean();
    }

    /**
     * Returns a backend wrapper for a specified namespace.
     *
     * @param string $namespace   Namespace.
     * @return Zend_Cache_Backend_Interface
     */
    private function _getBackendNamespaced($namespace)
    {
        if (!$this->_backend) {
            // Implement tags support too.
            $this->_backend = new Dklab_Cache_Backend_Profiler(
                new Dklab_Cache_Backend_TagEmuWrapper(
                    $this->getCleanBackend()
                ),
                array($this, '_profile')
            );
        }

        return new Dklab_Cache_Backend_NamespaceWrapper(
            $this->_backend,
            $namespace
        );
    }

    /**
     * Return Zend_Backend_* by config.ini params
     *
     * @return Zend_Backend_Interface
     */
    public function getCleanBackend()
    {
    	$cacheConfig = Config_Ini_Factory::factory('config_cache');
        $cache = $cacheConfig->cache_backend;
        if (!$cache->enable) {
        	$this->_cleanBackend = new Cache_Backend_Null();
        	return $this->_cleanBackend;
        }

        $class = $cache->class;
        $options = $cache->options;
		$this->_cleanBackend = new Dklab_Cache_Backend_TagEmuWrapper(new $class($options->toArray()));
		return $this->_cleanBackend;
    }

    /**
     * @todo Realize logger
     * Called from a backend profiler.
     *
     * @param float $dt         Time spent in calling.
     * @param string $method    Called method name.
     * @return void
     */
    public function _profile($dt, $method)
    {
    	return ;
        RuntimeStat::getInstance()->incParam(RuntimeStat::MMQ, 1);
        RuntimeStat::getInstance()->incParam(RuntimeStat::MMT, $dt);
    }
}
